<?php

class UsersTable extends Zend_Db_Table_Abstract
{
	protected $logger;
	protected $db;
	
	public function __construct($config = array())
	{
		$config['db'] = Zend_Registry::get('db');
		$config['name'] = 'users';
		$config['primary'] = 'user_id';
		parent::__construct($config);
		
		$this->logger = Zend_Registry::get('logger');
		$this->db = Zend_Registry::get('db');
	}
	
	public function addUser($name, $password, $email, $birthday)
	{
		try 
	    {
	    	$this->db->beginTransaction();
	        
			$user_id = $this->insert(array(
		                    'user_id'=>null,
		                    'name'=>$name,
		                    'password'=>$password
						));
	        
	        $user_infos = new UserInfosTable();
			$user_infos->AddUserInfo($user_id, 'email', $email);
			$user_infos->AddUserInfo($user_id, 'birthday', $birthday);
	        	
	        $this->db->commit();
	        $this->logger->info("User {$name} was added successfully");
			return $user_id;
	    }
	    catch (Exception $ex)
	    {
	    	$this->db->rollback();
	        $this->logger->err("User {$name} was not added. {$ex}");
	        throw $ex;
	    }
	}
	
	public function getAllUsers($sort_by)
	{
		$users = array();
		
		$select = $this->select()->order($sort_by);
		$user_rows = $this->fetchAll($select);
		
		$info_table = new UserInfosTable();
		foreach ($user_rows as $user_row)
		{
			$user_id = $user_row['user_id'];
			$user_info = $info_table->getAllInfo($user_id);
			
			$user_info['name'] = $user_row['name'];
			$user_info['create_date'] = $user_row['create_date'];
			
			$users[] = $user_info;
		}
		
		return $users;
	}
	
	public function getUserByName($name)
	{
		$select = $this->select()->where('name = ?', $name);
		$user_row = $this->fetchRow($select);
		if ($user_row != null)
		{
			$user_id = $user_row['user_id'];
			
			$info_table = new UserInfosTable();
			$user_info = $info_table->getAllInfo($user_id);
			
			$user_info['name'] = $user_row['name'];
			$user_info['password'] = $user_row['password'];
			$user_info['create_date'] = $user_row['create_date'];
			
			return $user_info;
		}
		else
		{
			return null;
		}
	}
}
?>
